package cn.hexcloud.dga.governance.assessor.spec;

import cn.hexcloud.dga.common.util.StringUtil;
import cn.hexcloud.dga.governance.assessor.Assessor;
import cn.hexcloud.dga.governance.bean.AssessParam;
import cn.hexcloud.dga.governance.bean.GovernanceAssessDetail;
import cn.hexcloud.dga.meta.bean.TableMetaInfo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Component("COLUMN_COMMENT")
public class ColumnCommentAssessor extends Assessor {
    @Override
    public void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws Exception {
        TableMetaInfo tableMetaInfo = assessParam.getTableMetaInfo();
        String colNameJson = tableMetaInfo.getColNameJson();
        if (colNameJson == null || colNameJson.trim().length() == 0) {
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
        } else {
            JSONArray jsonArray = JSONObject.parseArray(colNameJson);
            int colCount = jsonArray.size();
            int colCommentCount = 0;
            for (Object obj : jsonArray) {
                JSONObject colJSONObj = (JSONObject) obj;
                String comment = colJSONObj.getString("comment");
                if (!StringUtil.isEmpty(comment)) {
                    colCommentCount++;
                }
            }
            governanceAssessDetail.setAssessScore((BigDecimal.valueOf(colCommentCount * 10).divide(BigDecimal.valueOf(colCount),2, RoundingMode.HALF_DOWN)));
        }
        if(governanceAssessDetail.getAssessScore().compareTo(BigDecimal.TEN)<0){
            governanceAssessDetail.setAssessProblem("字段注释不全");
            String governanceUrl = assessParam.getGovernanceMetric().getGovernanceUrl().replace("{tableId}", tableMetaInfo.getId().toString());
            governanceAssessDetail.setGovernanceUrl(governanceUrl);
        }
    }
}
